/*
 * @Descripttion:
 * @version:
 * @Author: lsy
 * @Date: 2021-12-07 10:15:40
 * @LastEditors: lsy
 * @LastEditTime: 2021-12-17 11:24:39
 */
import axios from "axios";

export default {
    install: (app, { router, opt }) => {

        const instance = axios.create({
            timeout: 10 * 1000,
            headers: {
                post: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
                },
                'Content-Type': 'application/json'
            }
        })

        const requestError = error => Promise.reject(error);

        const beforeRequest = config => {
            if (!config.noToken) {
                config.headers.Authorization = `bearer ${localStorage.getItem('accessToken')}`;
            }
            return config;
        }

        const responseError = error => {
            if (error.response.status == 401) {
                router.push({ path: "/login" });
            }
            return Promise.reject(error)
        };

        const beforeResponse = res => {
            if (res.data.code == 1000 || res.data.code === 0 || res.data.code === '0') {
                return Promise.resolve(res)
            } else if (res.data.code == "27001007") {
                // token过期，刷新token
                return refreshToken().then(() => {
                    return instance.request(res.config)
                }, err => {
                    console.log(err)
                    // Message.error(`refreshToken 失效，请登录平台`)
                    router.push({ path: "/login" });
                    return Promise.reject(err)
                })
            } else {
                return Promise.reject(res)
            }
        }

        instance.interceptors.request.use(beforeRequest, requestError);
        instance.interceptors.response.use(beforeResponse, responseError);

        const method = {
            post: (url, p, config) => instance.post(url, p, config),
            get: (url, p, config) => instance.get(url, Object.assign(config, { params: p })),
            // put与patch区别：
            // put修改一个对象，必须传回去一个完整的对象，没有传的字段默认为空；
            // patch则只需传回被修改了的字段，后端只更新接收到的字段
            put: (url, p, config) => instance.put(url, p, config),
            patch: (url, p, config) => instance.put(url, p, config),
            delete: (url, p, config) => instance.delete(url, Object.assign(config, { params: p })),
        };

        let api = {};
        const files = require.context("@/api/", false, /\.js$/);

        files.keys().forEach(key => {
            const fileName = key.replace(/(\.\/|\.js)/g, "");
            api[fileName] = {};
            let obj = files(key);
            Object.keys(obj).forEach(item => {
                api[fileName][item] = (p, str = "") => {
                    let url = obj[item].url();
                    return method[obj[item].type](url + str, p, obj[item].config ? obj[item].config : {});
                }
            });
        });
        window[opt] = api;
        app.prototype[opt] = api;
    }
}

import qs from "qs";
// 刷新accessToken
function refreshToken() {
    var refreshToken = localStorage.getItem('refreshToken')
    var clientId = localStorage.getItem('checked') ? 'web_client_remember' : 'web_client'
    var value = {
        'refresh_token': refreshToken,
        'grant_type': 'refresh_token',
        'client_id': clientId,
        "client_secret": 'web_client'
    }
    return new Promise((resolve, reject) => {
        VE_API.system.refreshToken({}, `?${qs.stringify(value)}`).then(
            res => {
                localStorage.setItem("accessToken", res.data.data.access_token);
                localStorage.setItem('expiresTime', new Date().getTime() + res.data.data.expires_in * 1000);
                localStorage.setItem("refreshToken", res.data.data.refresh_token);
                localStorage.setItem("magicId", res.data.data.magicId);
                localStorage.setItem("userId", res.data.data.userId);
                resolve()
            },
            err => {
                reject(err)
            })
    })
}



